﻿using System;
using System.Data;
using System.IO;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AnyOffice.Components;
using AnyOffice.DAL;
using AnyOffice.Model;
using AnyOffice.BIZ;
using System.Reflection;
using log4net;
using Webdiver;

namespace AnyOffice.general.email
{
    public partial class _new :  ModulePage
    {

        private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);


        protected void btnAddFile_Click(object sender, EventArgs e)
        {
            if (this.fileAttach.PostedFile.ContentLength > 0)
            {
                try
                {
                    string uniqueTempPath = this.ViewState["UniqueTempPath"].ToString();
                    if (uniqueTempPath == "")
                    {
                        uniqueTempPath = AttachmentBiz.GetUniqueTempPath();
                        this.ViewState["UniqueTempPath"] = uniqueTempPath;
                    }
                    Upload upload = new Upload();
                    upload.AutoCreateDirectory = true;
                    upload.OverwriteFile = true;
                    upload.DestinationPath = uniqueTempPath;
                    ConfigManager manager = new ConfigManager();
                    upload.MaxSize = manager.AttachMaxSize;
                    upload.GetFile(this.fileAttach.PostedFile);
                    upload.DoUpload();
                    this.ViewState["TotalSize"] = Convert.ToInt32(this.ViewState["TotalSize"]) + upload.FileSize;
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    list.Add(Path.GetFileName(this.fileAttach.PostedFile.FileName));
                    this.ViewState["FileList"] = list;
                    this.ViewState["FileNums"] = Convert.ToInt32(this.ViewState["FileNums"].ToString()) + 1;
                    this.ltbFileList.Items.Add(Path.GetFileName(this.fileAttach.PostedFile.FileName));
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) != 0)
                    {
                        this.ltbFileList.Rows = Convert.ToInt32(this.ViewState["FileNums"].ToString());
                    }
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) > 0)
                    {
                        this.pnlAttach.Visible = true;
                    }
                }
                catch (Exception exception)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("附件添加", exception);
                    }
                }
            }
        }
        protected void btnRemoveFile_Click(object sender, EventArgs e)
        {
            if (this.ltbFileList.Items.Count != 0)
            {
                try
                {
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    list.Remove(this.ltbFileList.SelectedItem.Text);
                    this.ViewState["FileList"] = list;
                    string fileName = this.ViewState["UniqueTempPath"].ToString() + this.ltbFileList.SelectedItem.Text;
                    FileInfo info = new FileInfo(fileName);
                    if (info.Exists)
                    {
                        this.ViewState["TotalSize"] = Convert.ToInt32(this.ViewState["TotalSize"]) - info.Length;
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                    }
                    this.ViewState["FileNums"] = Convert.ToInt32(this.ViewState["FileNums"].ToString()) - 1;
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) >= 1)
                    {
                        this.ltbFileList.Rows = Convert.ToInt32(this.ViewState["FileNums"].ToString());
                    }
                    this.ltbFileList.Items.Remove(this.ltbFileList.SelectedItem.Text);
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) == 0)
                    {
                        if (Directory.Exists(this.ViewState["UniqueTempPath"].ToString()))
                        {
                            Directory.Delete(this.ViewState["UniqueTempPath"].ToString());
                        }
                        this.ViewState["UniqueTempPath"] = "";
                        this.pnlAttach.Visible = false;
                    }
                }
                catch (Exception exception)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("附件删除", exception);
                    }
                }
            }
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            string attachmentId = "";
            try
            {
                if (this.ViewState["UniqueTempPath"].ToString() != "")
                {
                    string uniquePath = AttachmentBiz.GetUniquePath(out attachmentId);
                    Directory.Move(this.ViewState["UniqueTempPath"].ToString(), uniquePath);
                    AttachmentData data = new AttachmentData();
                    AttachmentDao dao = new AttachmentDao();
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    for (int j = 0; j < list.Count; j++)
                    {
                        FileInfo info = new FileInfo(uniquePath + list[j].ToString());
                        if (info.Exists)
                        {
                            data.Type = 1;
                            data.AttachmentId = attachmentId;
                            data.Name = info.Name;
                            data.AddTime = DateTime.Now;
                            data.TotalSize = (int)info.Length;
                            data.UserId = base.User.Identity.Name;
                            dao.Insert(base.Conn, data);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("表单提交 - 附件上传相关", exception);
                }
            }
            EmailData data2 = new EmailData();
            EmailDao dao2 = new EmailDao();
            if (attachmentId != string.Empty)
            {
                data2.AttachmentId = attachmentId;
            }
            data2.ToId2 = this.ToId.Value;
            if (this.CopyToId.Value != string.Empty)
            {
                data2.CopyToId = this.CopyToId.Value;
            }
            if (this.SecretToId.Value != string.Empty)
            {
                data2.SecretToId = this.SecretToId.Value;
            }
            data2.FromId = base.User.Identity.Name;
            data2.Subject = this.txtSubject.Text;
            data2.TotalSize = (Convert.ToInt32(this.ViewState["TotalSize"].ToString()) + this.txtSubject.Text.Length) + this.txtContent.Value.Length;
            data2.Content = this.txtContent.Value;
            data2.Important = Convert.ToInt32(this.rblImportant.SelectedValue);
            string str3 = this.ToId.Value;
            if (this.CopyToId.Value != string.Empty)
            {
                str3 = str3 + this.CopyToId.Value;
            }
            if (this.SecretToId.Value != string.Empty)
            {
                str3 = str3 + this.SecretToId.Value;
            }
            if (str3.EndsWith(","))
            {
                str3 = str3.Substring(0, str3.Length - 1);
            }
            string[] strArray = str3.Split(new char[] { ',' });
            for (int i = 0; i < strArray.Length; i++)
            {
                data2.ToId = strArray[i];
                dao2.Insert(base.Conn, data2);
            }
            if (this.ckbSms.Checked || this.ckbMobile.Checked)
            {
                SmsData data3 = new SmsData();
                SmsDao dao3 = new SmsDao();
                data3.Type = 2;
                data3.FromId = base.User.Identity.Name;
                data3.ToIdList = str3;
                data3.Content = "请查收我的邮件！\n主题：" + this.txtSubject.Text;
                data3.RemindFlag = true;
                data3.SendTime = DateTime.Now;
                dao3.BizSend(base.Conn, data3, this.ckbSms.Checked, this.ckbMobile.Checked);
            }
            this.pnlMain.Visible = false;         
            this.lblMessage.Text = base.ShowPrompt("邮件已发送", "new.aspx");
            if (!this.ClientScript.IsStartupScriptRegistered(this.GetType(), "refresh"))
            {
               // this.ClientScript.RegisterStartupScript(this.GetType(), "refresh", " window.parent.mail_menu.location.reload();", true);
            }
         
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                UserCache cache = new UserCache();
                if ((cache.EmailCapacity != 0) && (new EmailBoxDao().InboxSize(base.Conn, base.User.Identity.Name) > ((cache.EmailCapacity * 1024) * 1024)))
                {
                    this.pnlMain.Visible = false;
                    this.lblMessage.Text = base.ShowWarning("您的邮箱已超过容量限制，请清除您的无用邮件！", "index.aspx");
                }
                else
                {
                    string str = (Request.QueryString["to_id"] != null) ? Request.QueryString["to_id"].ToString() : "";
                    if (str != string.Empty)
                    {
                        this.ToId.Value = str + ",";
                    }
                    string str2 = (Request.QueryString["to_name"] != null) ? Request.QueryString["to_name"].ToString() : "";
                    if (str2 != string.Empty)
                    {
                        this.ToName.Text = str2 + ",";
                    }
                    this.ViewState["FileNums"] = 0;
                    this.ViewState["FileList"] = new ArrayList();
                    this.ViewState["UniqueTempPath"] = "";
                    this.ViewState["TotalSize"] = 0;
                    this.btnAddFile.Attributes.Add("onclick", "return CheckFile();");
                    this.btnSend.Attributes.Add("onclick", "return CheckForm();");
                    this.ckbMobile.Visible = SmsDao.IsMobile(SmsDao.SmsType.Email);
                }
            }

            if (IsPostBack)
            {
                string str2 = (Request.QueryString["to_name"] != null) ? Request.QueryString["to_name"].ToString() : "";
                if (str2 != string.Empty)
                {
                    this.ToName.Text = str2 + ",";
                }
            
            
            }




        }
         

    }
}
